package thread;

import java.util.concurrent.locks.ReentrantLock;

public class ThreadCommunicationTest {
    private static boolean T2OUTPUT = false;
    private static boolean T3OUTPUT = false;
    private static boolean T1OUTPUT = true;

    private static final ReentrantLock lock = new ReentrantLock();

    public static void main(String[] args) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (lock) {
                    for (int i = 0; i < 10; i++) {
                        while (!T1OUTPUT) {
                            try {
                                lock.wait();
                            } catch (InterruptedException e) {
                                throw new RuntimeException(e);
                            }
                        }
                        System.out.println('A');
                        T1OUTPUT = false;
                        T2OUTPUT = true;
                        T3OUTPUT = false;
                        lock.notifyAll();
                    }
                }
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (lock) {
                    for (int i = 0; i < 10; i++) {
                        while (!T2OUTPUT) {
                            try {
                                lock.wait();
                            } catch (InterruptedException e) {
                                throw new RuntimeException(e);
                            }
                        }
                        System.out.println('B');
                        T1OUTPUT = false;
                        T2OUTPUT = false;
                        T3OUTPUT = true;
                        lock.notifyAll();
                    }
                }

            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (lock) {
                    for (int i = 0; i < 10; i++) {
                        while (!T3OUTPUT) {
                            try {
                                lock.wait();
                            } catch (InterruptedException e) {
                                throw new RuntimeException(e);
                            }
                        }
                        System.out.println('C');
                        T1OUTPUT = true;
                        T2OUTPUT = false;
                        T3OUTPUT = false;
                        lock.notifyAll();
                    }
                }
            }
        }).start();
    }
}

